//
// Create by Zeng Yun on 2018/12/21
//

package model

import (
	"adai.design/jarvis/common/db"
	"github.com/globalsign/mgo/bson"
)

type homeManager struct{}

// 新建家庭
// name: 家庭名
// admin: 主人账号ID
func (hm *homeManager) Insert(name, admin string) (*HMHome, error) {
	session, err := db.GetSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()
	collection := session.DB("home").C("home")

	h := &HMHome{
		HomeInfo: HomeInfo{
			Id:      db.NewId(),
			Name:    name,
			Version: 0,
			Members: []*Member{{Id: admin, Role: MemberRoleAdmin}},
		},
	}
	err = collection.Insert(h)
	if err != nil {
		return nil, err
	}
	return h, nil
}

// 移除家庭
func (hm *homeManager) Remove(id string) error {
	session, err := db.GetSession()
	if err != nil {
		return err
	}
	defer session.Close()
	collection := session.DB("home").C("home")

	err = collection.Remove(bson.M{"id": id})
	return err
}

// 更新家庭数据
func (hm *homeManager) Update(h *HMHome) error {
	session, err := db.GetSession()
	if err != nil {
		return err
	}
	defer session.Close()
	collection := session.DB("home").C("home")

	err = collection.Update(bson.M{"id": h.Id}, h)
	return err
}

// 查找所有家庭
func (hm *homeManager) FindAll() ([]*HomeInfo, error) {
	session, err := db.GetSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()
	collection := session.DB("home").C("home")

	var hs []*HomeInfo
	err = collection.Find(bson.M{}).All(&hs)
	if err != nil {
		return nil, err
	}
	return hs, nil
}

// 通过ID查找账号
func (hm *homeManager) FindById(id string) (*HMHome, error) {
	session, err := db.GetSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()
	collection := session.DB("home").C("home")

	var h HMHome
	err = collection.Find(bson.M{"id": id}).One(&h)
	if err != nil {
		return nil, err
	}
	return &h, nil
}

// 家庭管理
var Homes = homeManager{}
